import CryptoJS from 'crypto-js';
// aes加密
function encrypt(str,mykey,myiv) {
	var key = CryptoJS.enc.Utf8.parse(mykey);
	var iv = CryptoJS.enc.Utf8.parse(myiv);
	var encrypted = '';
	var srcs = CryptoJS.enc.Utf8.parse(str);
	var encrypted = CryptoJS.AES.encrypt(srcs, key, {
		iv:iv,
		mode:CryptoJS.mode.CBC,
		padding:CryptoJS.pad.Pkcs7,
	});
	//return encrypted;
	return encrypted.ciphertext.toString();
}

// aes解密
function decrypt(str,mykey,myiv){
	var key = CryptoJS.enc.Utf8.parse(mykey);
	var iv = CryptoJS.enc.Utf8.parse(myiv);
	var encryptedHexStr = CryptoJS.enc.Hex.parse(str);
	var srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
	var decrypt = CryptoJS.AES.decrypt(srcs,key,{
		iv:iv,
		mode:CryptoJS.mode.CBC,
		padding:CryptoJS.pad.Pkcs7
	}) 
	return CryptoJS.enc.Utf8.stringify(decrypt).toString();
}

// 根据平台封装的简单提示
function toast(str){
	uni.showToast({
		title: str,
		icon:"none",
		duration: 2000
	});
}

// 成功的提示
function sucToast(str)
{
	uni.showToast({
		title:str,
		icon: "success",
		duration:2000
	})
}

// 加载提示
function showLoading(str)
{
	uni.showLoading({
	    title: str
	});
}

// 关闭加载提示
function hideLoading(str)
{
	uni.hideLoading();
}

// 获取时间戳
function getTimestamp()
{
	return new Date().getTime();
}

// 校验是否登录
function checkLogin(){
	const islogin = uni.getStorageSync('isLogin'); //isLogin是登录成功后在本地存储登录标识
	if (islogin) return true;
	else return false;
}

// 本地存储
function saveStorage(str,val){
	console.log('本地缓存:'+str+'，值：'+val);
	uni.setStorageSync(str, val);
}

// 读取本地存储
function readStorage(str){
	console.log('准备读取缓存:'+str);
	let val = uni.getStorageSync(str);
	console.log('准备读取缓存:'+str+',得到'+val);
	return val;
}

export default {
	toast:toast,
	showLoading:showLoading,
	hideLoading:hideLoading,
	sucToast:sucToast,
	getTimestamp:getTimestamp,
	checkLogin:checkLogin,
	encrypt:encrypt,
	decrypt:decrypt,
	saveStorage:saveStorage,
	readStorage:readStorage
};